/**
 * @date 2005-12-12 12:46:49
 *
 */
package org.nanhill.xsheet.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nanhill.commons.model.table.Table;

/**
 * @author alin
 * 
 */
public class XSheetModel {
	private Map<Integer, XSheetStyle> styles;

	private List<Table> tables;

	public XSheetModel() {
		this.tables = new ArrayList<Table>();
		this.styles = new HashMap<Integer, XSheetStyle>();
	}

	public void addStyle(XSheetStyle style) {
		this.styles.put(style.getId(), style);
	}

	public XSheetStyle getStyle(int styleId) {
		return this.styles.get(styleId);
	}

	public XSheetStyle[] getStyles() {
		Collection<XSheetStyle> stylesCollection = styles.values();
		return stylesCollection
				.toArray(new XSheetStyle[stylesCollection.size()]);
	}

	public List<Table> getTables() {
		return tables;
	}

	public Table getTable(int index) {
		return tables.get(index);
	}

	public void setTables(List<Table> tables) {
		this.tables = tables;
	}

	public Table createTable(int tableIndex) {
		return createTable(tableIndex, null);
	}

	public Table createTable(String tableName) {
		Table table = new Table(tableName);
		this.tables.add(table);
		return table;
	}

	public Table createTable() {
		return createTable("");
	}

	public Table createTable(int tableIndex, String tableName) {
		Table table;
		int size = this.tables.size();
		// if cell index is overflow cells
		if (tableIndex > size - 1) {
			// fill the cells with null
			for (int i = size; i < tableIndex; i++) {
				this.tables.add(null);
			}
			table = new Table(tableName);
			this.tables.add(table);
		} else {
			table = this.tables.get(tableIndex);
			if (null == table) {
				this.tables.remove(tableIndex);
				table = new Table(tableName);
				this.tables.add(tableIndex, table);
			}
		}
		return table;
	}

}
